import Select from "ant-design-vue/es/select";
import "ant-design-vue/lib/select/style/css";

const { Option } = Select;
export default {
  name: "FormSelect",
  props: {
    option: {
      type: Object,
      default() {
        return {};
      }
    },
    value: [String, Number, Array]
  },
  model: {
    prop: "value",
    event: "updata"
  },
  data() {
    return {
      data: []
    };
  },
  computed: {
    valueField() {
      return this.option.valueField ? this.option.valueField : "id";
    },
    textField() {
      return this.option.textField ? this.option.textField : "text";
    }
  },
  created() {
    if (this.option.data) {
      this.setData(this.option.data);
    }
  },
  methods: {
    onChange(value) {
      const that = this;
      let sel = "";
      if (typeof value === "object") {
        const selects = this.data.filter(
          item => value.indexOf(item[that.valueField]) > -1
        );
        sel = selects;
      } else {
        const selects = this.data.filter(
          item => item[that.valueField] === value
        );
        sel = selects.length === 1 ? selects[0] : {};
      }

      this.$emit("updata", value);
      this.$emit("change", value, sel);
    },
    setFocus(is) {
      if (is) {
        this.$refs.formSelect.focus();
      } else {
        this.$refs.formSelect.blur();
      }
    },
    setData(data) {
      this.data = data;
    }
  },
  render() {
    const that = this;
    const options = {
      ref: "formSelect",
      props: {
        allowClear: true,
        // value: "",
        ...this.option.props
      },
      on: {
        ...this.option.on,
        change: e => {
          that.onChange(e);
        },
        focus: e => {
          this.$emit("focus", e);
        },
        blur: e => {
          this.setFocus(false);
          this.$emit("blur", e);
        }
      }
    };
    if (typeof this.value === "object") {
      options.props.value = this.value;
    } else if (
      this.option.props &&
      this.option.props.mode === "multiple" &&
      !this.value
    ) {
      options.props.value = [];
    } else if (typeof this.value === "number") {
      options.props.value = this.value + "";
    } else if (this.value) {
      options.props.value = this.value;
    }

    //关键词搜索时，接管filterOption,增加obj数据返回
    if (options.props.filterOption) {
      options.props.filterOption = (input, option) => {
        const value = option.componentOptions.propsData.value;
        const objIndex = this.data.findIndex(
          item => item[this.valueField] + "" === value
        );
        const obj = this.data[objIndex];
        return this.option.props.filterOption(input, option, obj);
      };
    }

    const items = this.data.map(item => {
      return (
        <Option value={item[this.valueField] + ""}>
          {item[this.textField]}
        </Option>
      );
    });

    return <Select {...options}>{items}</Select>;
  }
};
